//var  api_base_url=

/**
 * 公用方法
 */
var Common = {

	/**
	 * 无参数ajax
	 * 
	 * @param {Object}
	 *            reqUrl
	 * @param {Object}
	 *            succCalback
	 */
	ajaxNoParamGet: function(reqUrl, succCalback) {
		var ii = layer.load();
		$.ajax({
			type: "get",
			url: reqUrl,
			dataType: 'json',
			success: function(data) {
				layer.close(ii);
				if(data.code == "200") {
					var index = eval('(' + data.data + ')');
					if(typeof(succCalback) != "undefined")
						succCalback(index);
				} else if(data.code == "103") {
					location.href = "login.html"
				} else {
					layer.msg(data.message);
				}
			},
			error: function() {
				layer.close(ii);
				layer.msg('请求失败');
			}

		});
	},
	/**
	 * 无参数ajax
	 * 
	 * @param {Object}
	 *            reqUrl
	 * @param {Object}
	 *            succCalback
	 */
	ajaxNoParamPost: function(reqUrl, succCalback) {
		var ii = layer.load();
		$.ajax({
			type: "post",
			url: reqUrl,
			dataType: 'json',
			success: function(data) {
				layer.close(ii);
				if(data.code == "200") {
					var index = eval('(' + data.data + ')');
					if(typeof(succCalback) != "undefined")
						succCalback(index);
				} else if(data.code == "103") {
					location.href = "login.html"
				} else {
					layer.msg(data.message);
				}
			},
			error: function() {
				layer.close(ii);
				layer.msg('请求失败');
			}

		});
	},
	/**
	 * 带参数ajax,asyFlag异步开关，默认异步
	 * 
	 * @param {Object}
	 *            reqUrl
	 * @param {Object}
	 *            params
	 * @param {Object}
	 *            succCalback
	 */
	ajaxWithParam: function(reqUrl, params, succCalback, asyFlag) {
		var ii = layer.load();
		var flag = true;
		if(asyFlag != undefined) {
			flag = asyFlag;
		}
		$.ajax({
			type: "post",
			url: reqUrl,
			dataType: 'json',
			data: params,
			async: flag,
			success: function(data) {
				layer.close(ii);
				if(data.code == "200") {
					var index = eval('(' + data.data + ')');
					if(typeof(succCalback) != "undefined")
						succCalback(index);
				} else if(data.code == "103") {
					location.href = "login.html"
				} else {
					layer.msg(data.message);
				}
			},
			error: function() {
				layer.close(ii);
				layer.msg('请求失败');
				if(typeof(timer) != "undefined") {
					clearInterval(timer);
				}
			}
		});
	},

    /**
     * 带参数ajax,asyFlag异步开关，默认异步
     *
     * @param {Object}
     *            reqUrl
     * @param {Object}
     *            params
     * @param {Object}
     *            succCalback
     */
    ajaxWithParamGet: function(reqUrl, params, succCalback, asyFlag) {
        var ii = layer.load();
        var flag = true;
        if(asyFlag != undefined) {
            flag = asyFlag;
        }
        $.ajax({
            type: "get",
            url: reqUrl,
            dataType: 'json',
            data: params,
            async: flag,
            success: function(data) {
                layer.close(ii);
                if(data.code == "200") {
                    var index = eval('(' + data.data + ')');
                    if(typeof(succCalback) != "undefined")
                        succCalback(index);
                } else if(data.code == "103") {
                    location.href = "login.html"
                } else {
                    layer.msg(data.message);
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('请求失败');
                if(typeof(timer) != "undefined") {
                    clearInterval(timer);
                }
            }
        });
    },

    /**
     * 带参数ajax,asyFlag异步开关，默认异步，不处理返回值
     *
     * @param {Object}
     *            reqUrl
     * @param {Object}
     *            params
     * @param {Object}
     *            succCalback
     */
    ajaxWithParamBack: function(reqUrl, params, succCalback, asyFlag) {
        var ii = layer.load();
        var flag = true;
        if(asyFlag != undefined) {
            flag = asyFlag;
        }
        $.ajax({
            type: "post",
            url: reqUrl,
            dataType: 'json',
            data: params,
            async: flag,
            success: function(data) {
                layer.close(ii);
                if(typeof(succCalback) != "undefined"){
                    succCalback(data);
				}

            },
            error: function() {
                layer.close(ii);
                layer.msg('请求失败');
                if(typeof(timer) != "undefined") {
                    clearInterval(timer);
                }
            }
        });
    },

	/**
	 * 根据key获取参数的值
	 * 
	 * @param name
	 * @returns
	 */
	queryGetParam: function queryGetParam(name) {
		var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		var r = window.location.search.substr(1).match(reg);
		if(r != null) {
			return decodeURI(r[2]);
		}
		return null;
	},

	/**
	 * 上传图片
	 * 
	 * @param fileId
	 */
	uploadPic: function uploadPic(uploadForm, fileId, imgId) {
		var iMaxFilesize = 10097152; // 10M
		var url = null;
		window.fileSelected = function() {
			var ii = layer.load();
			var oFile = document.getElementById(fileId).files[0]; // 读取文件
			var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
			if(!rFilter.test(oFile.type)) {
				layer.close(ii);
				layer.msg("文件格式必须为图片");
				return;
			}
			if(oFile.size > iMaxFilesize) {
				layer.close(ii);
				layer.msg("图片大小不能超过10M");
				return;
			}
			var vFD = new FormData(document.getElementById(uploadForm)), // 建立请求和数据
				oXHR = new XMLHttpRequest();
			oXHR.addEventListener('load', function(resUpload) {
				// 成功
				console.log(resUpload.currentTarget.response);
				var json = eval('(' + resUpload.currentTarget.response + ')');
				var index = eval('(' + json.data + ')');
				// 得到图片url
				url = index.url;
				// 展示图片
				$("#" + imgId).attr("src", index.url);
			}, false);
			oXHR.addEventListener('error', function() {
				// 失败
			}, false);
			oXHR.addEventListener('abort', function() {
				// 上传中断
			}, false);
			oXHR.open('POST', "/api/h5/common/upload");
			oXHR.send(vFD);
			layer.close(ii);
		}
	},
	
	/**
	 * 上传图片
	 * 
	 * @param fileId
	 */
	uploadPic: function uploadPic(uploadForm, fileId, imgId) {
		var iMaxFilesize = 10097152; // 10M
		var url = null;
		window.fileSelected = function() {
			var ii = layer.load();
			var oFile = document.getElementById(fileId).files[0]; // 读取文件
			var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
			if(!rFilter.test(oFile.type)) {
				layer.close(ii);
				layer.msg("文件格式必须为图片");
				return;
			}
			if(oFile.size > iMaxFilesize) {
				layer.close(ii);
				layer.msg("图片大小不能超过10M");
				return;
			}
			var vFD = new FormData(document.getElementById(uploadForm)), // 建立请求和数据
				oXHR = new XMLHttpRequest();
			oXHR.addEventListener('load', function(resUpload) {
				// 成功
				console.log(resUpload.currentTarget.response);
				var json = eval('(' + resUpload.currentTarget.response + ')');
				var index = eval('(' + json.data + ')');
				// 得到图片url
				url = index.url;
				// 展示图片
				$("#" + imgId).attr("src", index.url);
			}, false);
			oXHR.addEventListener('error', function() {
				// 失败
			}, false);
			oXHR.addEventListener('abort', function() {
				// 上传中断
			}, false);
			oXHR.open('POST', "/fenful/api/v1/common/");
			oXHR.send(vFD);
			layer.close(ii);
		}
	},
	

	/**
	 * 登录信息
	 */
	getLoginInfo: function() {
		var token = window.localStorage.getItem("token");
		var phoneNum = window.localStorage.getItem("phoneNum");
		var userType = window.localStorage.getItem("userType");
		var userId = window.localStorage.getItem("userId");
		if(phoneNum == null || phoneNum == '' || token == null || token == '') {
			// return null;
			window.location.href = this.getRootPath() + "/h5/login.html";
		}
		var str = {};
		str.phoneNum = phoneNum;
		str.token = token;
		str.userType = userType;
		str.userId = userId;

		return str;
	},

	setLoginInfo: function(phoneNum, token, userType, userId) {
		window.localStorage.setItem("phoneNum", phoneNum);
		window.localStorage.setItem("token", token);
		window.localStorage.setItem("userType", userType);
		window.localStorage.setItem("userId", userId);
	},

	

	
	

	/**
	 * 生成32位主键UUID
	 */
	getUuid: function() {
		var s = [];
		var hexDigits = "0123456789abcdef";
		for(var i = 0; i < 36; i++) {
			s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
		}
		s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
		s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the
		// clock_seq_hi_and_reserved
		// to 01
		// s[8] = s[13] = s[18] = s[23] = "-";
		var uuid = s.join("");
		return uuid;
	},

	/**
	 * 得到所有的input和select值
	 */
	getModelData: function(el) {
		var model = {};
		var $this = $("#" + el);
		$this.find("input").each(function(index, element) {
			var id = $(element).attr("id");
			if(id) {
				model[id] = $(element).val();
			}
		});
		$this.find("select").each(function(index, element) {
			var id = $(element).attr("id");
			if(id) {
				model[id] = $(element).val();
			}
		});
		$this.find("textarea").each(function(index, element) {
			var id = $(element).attr("id");
			if(id) {
				model[id] = $(element).val();
			}
		});
		return model;
	},

	/**
	 * 检查必填项
	 */
	checkRequired: function(el) {
		var $this = $("#" + el);
		var flag = true;
		$this.find(".required").each(function(index, element) {
			if(!$(element).val()) {
				flag = false;
				$(element).focus();
				return false;
			}
		});
		return flag;
	},
    /**
     * 是否为正整数  
     * @param {Object} s
     */
	isPositiveNum: function isPositiveNum(s) { 
		var re = /^[0-9]*[1-9][0-9]*$/;
		return re.test(s)
	},
    /**
     * 是否指定倍数
     * @param {Object} s
     * @param {Object} x
     */
    isMultiple: function isMultiple(s,x){
    	if(s % x == 0){
    		return true;
    	}else{
    		return false;
    	}
    },
    
    toast:function toast(s){
    	layer.msg(s);
    },
    				

    isEmpty:function isEmpty(s,a){
    	if(s==''||s==null||typeof(s)=="undefined"){
    		layer.msg(a);
    		return ;
    	}
    },

    /**
	 * 判断是否是手机号，返回Boolean值
     * @param str
     * @returns {boolean}
     */
	isPhoneNumber:function(str){
        var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
        if (!myreg.test(str)) {
            return false;
        } else {
            return true;
        }
    },
    /**
	 * 格式化日期 yyyy-MM-dd hh:mm:ss
     * @param dt
     * @param format
     * @returns {*}
     */
    dateFormat:function(dt,format){
        var o = {
            "M+" : dt.getMonth()+1, //month
            "d+" : dt.getDate(),    //day
            "h+" : dt.getHours(),   //hour
            "m+" : dt.getMinutes(), //minute
            "s+" : dt.getSeconds(), //second
            "q+" : Math.floor((dt.getMonth()+3)/3),  //quarter
            "S" : dt.getMilliseconds() //millisecond
        }
        if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
            (dt.getFullYear()+"").substr(4 - RegExp.$1.length));
        for(var k in o)if(new RegExp("("+ k +")").test(format))
            format = format.replace(RegExp.$1,
                RegExp.$1.length==1 ? o[k] :
                    ("00"+ o[k]).substr((""+ o[k]).length));
        return format;
    },

    /**
     * 格式化html模板语言,defaul用什么填充空数据，默认 无
     */
    formatTemplate : function(dta, tmpl,defaul) {
        var format = {
            name : function(x) {
                return x;
            }
        };
        var nochar = "无";
        if(defaul!=undefined){
            nochar = defaul;
        }
        return tmpl.replace(/{(\w+)}/g, function(m1, m2) {
            if (!m2)
                return "";
            //return (format && format[m2]) ? format[m2](dta[m2]) : dta[m2];
            return (dta[m2])||(dta[m2]=="0") ? dta[m2] : nochar;
        });
    },
    /**
	 * 系统url路径
     */
	//WEB_PATH:"http://api.fenful.com"
    WEB_PATH:"http://api.fenful.com"
};